package com.my.study.collections.ergodic;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;

/**
 * 变量Map工具类
 *
 * @author: yidujun
 * @create: 2021/03/23 17:06
 */
public final class ErgodicMapUtils {

    public static <K, V> Map.Entry<K, V> getHeadByIterator(Map<K, V> map) {
        return map.entrySet().iterator().next();
    }

    @SuppressWarnings("unchecked")
    public static <K, V> Map.Entry<K, V> getHeadByReflect(Map<K, V> map) {
        try {
            Field head = map.getClass().getDeclaredField("head");
            head.setAccessible(true);
            return (Map.Entry<K, V>) head.get(map);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            return null;
        }
    }

    public static <K, V> Map.Entry<K, V> getTailByIterator(Map<K, V> map) {
        Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
        Map.Entry<K, V> tail = null;
        while (iterator.hasNext()) {
            tail = iterator.next();
        }
        return tail;
    }

    @SuppressWarnings("unchecked")
    public static <K, V> Map.Entry<K, V> getTailByReflect(Map<K, V> map) {
        try {
            Field tail = map.getClass().getDeclaredField("tail");
            tail.setAccessible(true);
            return (Map.Entry<K, V>) tail.get(map);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            return null;
        }
    }
}
